package org.travel.travel2gether.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.travel.travel2gether.domain.Track;
import org.travel.travel2gether.dto.TrackForm;
import org.travel.travel2gether.service.TrackService;

@Controller
@RequestMapping(value = "track")
public class TrackController {
	public final static String ATTR_TRACK_FORM = "trackForm";
	public final static String ATTR_AUTH_TYPE = "authType";
	public final static String ATTR_AUTH_FB = "fb";
	public final static String ATTR_AUTH_EMAIL = "email";
	
	@Autowired TrackService trackService;
	
	//not secured
	@RequestMapping(value = "new")
	public TrackForm newTrack(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute(ATTR_TRACK_FORM);
		if( attribute != null ) {
			return (TrackForm)attribute;
		}
		return new TrackForm();
	}

	@RequestMapping(value = "new", method = RequestMethod.POST)
	public String addTrack(@Valid @ModelAttribute TrackForm trackForm, Errors errors, 
			HttpServletRequest request) {
		if (errors.hasErrors()) {
			return null;
		}
		HttpSession session = request.getSession();
		session.setAttribute(ATTR_TRACK_FORM, trackForm);
		boolean isAuthenticated = request.getUserPrincipal() != null;
		String authType = request.getParameter(ATTR_AUTH_TYPE);
		if(isAuthenticated) {
			
			Track track = trackService.addTrack(trackForm);
			
			return "redirect:/track/" + track.getId();
			
			
		} else if(ATTR_AUTH_FB.equals(authType)) {
			session.setAttribute("redirect", "track/new");
			return "redirect:/facebookLogin";
		} else if(ATTR_AUTH_EMAIL.equals(authType)) {
			session.setAttribute("redirect", "track/new");
			return "redirect:/signin";
		}
		
		return null;
	}

	@RequestMapping(value="/{id}")
	public String getById(@PathVariable Long id,ModelAndView modelAndView){
		Track track = trackService.findOne(id);
		modelAndView.addObject("track", track);
		return "track";
	}
}
